package logic

import (
	"backend/apps/book/models"
	"context"
	"database/sql"
	"github.com/pkg/errors"

	"backend/apps/book/proto"
	"backend/apps/book/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateBookLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateBookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateBookLogic {
	return &UpdateBookLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateBookLogic) UpdateBook(in *proto.Book) (*proto.CommonResponse, error) {
	_, err := l.svcCtx.BookModel.FindOne(l.ctx, in.Id)
	if err != nil {
		if errors.Is(err, models.ErrNotFound) {
			return nil, errors.New("书籍信息不存在")
		}
		return nil, err
	}

	err = l.svcCtx.BookModel.Update(l.ctx, &models.Book{
		Id:       in.Id,
		Title:    in.Title,
		CoverUrl: in.CoverUrl,
		Summary: sql.NullString{
			String: in.Summary,
			Valid:  true,
		},
		TotalWords: in.TotalWords,
		Status:     int64(in.Status),
		IsVip:      int64(in.IsVip),
	})
	return &proto.CommonResponse{}, err
}
